package edu.stanford.prpl.app.prpltalk.android;

import java.util.Map;
import java.util.Vector;
import java.util.Iterator;
import java.util.Arrays;
import java.lang.Integer;

import edu.stanford.prpl.app.prpltalk.PRPLTalk;
import edu.stanford.prpl.app.prpltalk.PRPLTalk.BuddyInfo;
import edu.stanford.prpl.app.prpltalk.android.R.id;
import edu.stanford.prpl.app.prpltalk.android.R.layout;
import edu.stanford.prpl.app.prpltalk.android.R.string;
import edu.stanford.prpl.api.PRPLAppClient;
import edu.stanford.prpl.common.util.URIUtils;
import edu.stanford.prpl.common.PRPLProperties;

import android.util.Log;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnCancelListener;

public class ContactsPage extends Activity {
	private static final int ACTIVITY_ADD_CONTACT = 0;
	private static final int ACTIVITY_DELETE_CONTACT = 1;
	private static final int ACTIVITY_CHAT = 2;

	public static final String KEY_CHAT_SESSION_ID = "chat_session_id";

	private static final int CHAT_ID = Menu.FIRST;
	private static final int CONFIG_ID = Menu.FIRST + 1;
	private static final int LIST_CHATS_ID = Menu.FIRST + 2;
	private static final int ADD_CONTACT_ID = Menu.FIRST + 3;
	private static final int EDIT_CONTACT_ID = Menu.FIRST + 4;
	private static final int DELETE_CONTACT_ID = Menu.FIRST + 5;

	private static final String TAG = "MyActivity";

	// List of contacts selected (by email identifiers)
	private Vector<String> contactsSelected;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts_page);
		setTitle("PrPlTalk");
		contactsSelected = new Vector<String>();

		Log.d(TAG, "PrPlUserKey: " + PRPLProperties.getProperty("prpl.user.key"));
		Log.d(TAG, "PrPlDirUrl: " + PRPLProperties.getProperty("prpl.directory.url"));

		Log.d(TAG, "NUMBER OF COMMUNICATION RESOURCES # "
				+ PrPlTalkActivity.prplTalk.getAllCommunicationResources().length);
		// prplTalk.synchWithAll();
	}

	@Override
	protected void onResume() {
		Log.d(TAG, "On Resume() called!");

		drawContactsUI();
		Log.d(TAG, "Formatted contacts page!");
		super.onResume();
	}

	public void drawContactsUI() {
		// Get contacts/buddies from PrPl
		Log.d(TAG, "Getting Buddies list...");
		BuddyInfo[] contactsArray = PrPlTalkActivity.prplTalk.getBuddyList();
		Log.d(TAG, "Got the Buddies list...");
		ContactManager.getInstance().clearContactManager();
		ContactManager.getInstance().updateAllContacts(contactsArray);

		Map<String, Contact> contactsMap = ContactManager.getInstance().getAllContacts();
		// LinearLayout row;
		LayoutInflater theInflater = getWindow().getLayoutInflater();

		View contactsRow = theInflater.inflate(R.layout.contacts_row, null);
		LinearLayout contactContainer;
		ImageButton contactButton;
		TextView contactLabel;

		// Container containing rows of contact icons
		// should be cleared each time there is a redraw.
		LinearLayout contactList = (LinearLayout) this.findViewById(R.id.contacts_list);
		contactList.removeAllViews();
		contactsSelected.clear();

		int i = 0;
		for (String contactEmail : contactsMap.keySet()) {
			i++;
			if ((i % 3) == 1) {
				// row = new LinearLayout(this);
				// row.setOrientation(LinearLayout.HORIZONTAL);

				contactsRow = theInflater.inflate(R.layout.contacts_row, null);
				// use addView() somewhere
				contactList.addView(contactsRow);
			}

			if ((i % 3) == 1) {
				contactContainer = (LinearLayout) contactsRow.findViewById(R.id.contact1);
				contactButton = (ImageButton) contactsRow.findViewById(R.id.contact_button1);
				contactLabel = (TextView) contactsRow.findViewById(R.id.contact_label1);
			} else if ((i % 3) == 2) {
				contactContainer = (LinearLayout) contactsRow.findViewById(R.id.contact2);
				contactButton = (ImageButton) contactsRow.findViewById(R.id.contact_button2);
				contactLabel = (TextView) contactsRow.findViewById(R.id.contact_label2);
			} else {
				contactContainer = (LinearLayout) contactsRow.findViewById(R.id.contact3);
				contactButton = (ImageButton) contactsRow.findViewById(R.id.contact_button3);
				contactLabel = (TextView) contactsRow.findViewById(R.id.contact_label3);
			}

			BuddyInfo bInfo = contactsMap.get(contactEmail).getContactPrPlInfo();
			if (bInfo.photoResource != null) {
				Bitmap bm = BitmapFactory.decodeStream(bInfo.photoResource.getBlob());
				bm = Bitmap.createScaledBitmap(bm, 64, 64, true);
				contactButton.setImageBitmap(bm);
			}

			contactContainer.setVisibility(View.VISIBLE);
			contactLabel.setText(contactsMap.get(contactEmail).getName());
			initializeButton(contactButton, contactLabel, contactEmail);

			Log.d(TAG, "Contact button " + i + " has been initialized!");
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, CHAT_ID, 0, R.string.chat).setIcon(R.drawable.chat);
		menu.add(0, CONFIG_ID, 0, R.string.edit_your_contact).setIcon(R.drawable.configuration);
		menu.add(0, LIST_CHATS_ID, 0, R.string.list_chats).setIcon(R.drawable.list_chats);
		menu.add(0, ADD_CONTACT_ID, 0, R.string.add_contact).setIcon(R.drawable.add_contact);
		menu.add(0, EDIT_CONTACT_ID, 0, R.string.edit_contact).setIcon(R.drawable.edit_contact);
		menu.add(0, DELETE_CONTACT_ID, 0, R.string.delete_contact).setIcon(R.drawable.delete_contact);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent i;

		switch (item.getItemId()) {
		case CHAT_ID:
			if ((contactsSelected == null) || contactsSelected.isEmpty())
				return true;
			
			// Create a new chat session
			String sessionId = null;
			// String sessionId = PrPlTalkActivity.prplTalk.resourceURI2sessionId(resource.getURI());

			String identities[] = contactsSelected.toArray(new String[] {});
			for (int j = 0; j < identities.length; j++) {
				identities[j] = URIUtils.getIdentityURI(identities[j]);
			}
			sessionId = PrPlTalkActivity.prplTalk.startSession(identities);
			// SessionWindow sessionWindow = new SessionWindow(prplTalk, sessionId);
			// sessionWindow.start();
			ChatSessionManager.getInstance().startChatSession(sessionId, contactsSelected);

			Log.d(TAG, "Created session (" + sessionId + ") with " + Arrays.toString(identities));

			i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.ChatPage");
			i.putExtra(ContactsPage.KEY_CHAT_SESSION_ID, sessionId);
			startActivityForResult(i, ACTIVITY_CHAT);

			return true;

		case CONFIG_ID:
			i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.EditContact");
			i.putExtra(EditContact.KEY_CONTACT_TYPE, EditContact.ACTIVITY_EDIT_PERSONAL_CONTACT);
			startActivityForResult(i, EditContact.ACTIVITY_EDIT_PERSONAL_CONTACT);
			return true;

		case ADD_CONTACT_ID:
			i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.EditContact");
			i.putExtra(EditContact.KEY_CONTACT_TYPE, EditContact.ACTIVITY_ADD_NEW_CONTACT);
			startActivityForResult(i, EditContact.ACTIVITY_ADD_NEW_CONTACT);
			return true;
		case EDIT_CONTACT_ID: {
			if ((contactsSelected == null) || contactsSelected.isEmpty())
				return true;

			Iterator<String> itrTemp = contactsSelected.iterator();
			String contactsTaken = "";
			while (itrTemp.hasNext()) {
				String emailID = (String) itrTemp.next();
				contactsTaken += "\n" + ContactManager.getInstance().getContact(emailID).getName();
			}
			Log.d(TAG, "The following are currently selected " + contactsTaken);
			Log.d(TAG, "The chat session ID being edited is " + contactsSelected.firstElement());

			i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.EditContact");
			i.putExtra(EditContact.KEY_CONTACT_TYPE, EditContact.ACTIVITY_EDIT_OTHER_CONTACT);
			i.putExtra(EditContact.KEY_CONTACT_ID, contactsSelected.firstElement());
			startActivityForResult(i, EditContact.ACTIVITY_EDIT_OTHER_CONTACT);
			return true;
		}
		case DELETE_CONTACT_ID: {
			if ((contactsSelected == null) || contactsSelected.isEmpty())
				return true;

			Iterator<String> itr1 = contactsSelected.iterator();
			String contactsToBeDeleted = "";
			while (itr1.hasNext()) {
				String emailID = (String) itr1.next();
				contactsToBeDeleted += "\n" + ContactManager.getInstance().getContact(emailID).getName();
			}

			new AlertDialog.Builder(this).setTitle("Delete Contact").setMessage(
					"Are you sure you wish to delete the following contacts?" + contactsToBeDeleted)
					.setPositiveButton("Yes", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							ContactManager.getInstance().deleteContacts(contactsSelected);
							contactsSelected.clear();
							drawContactsUI();
							return;
						}
					}).setNegativeButton("Cancel", new OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					}).setOnCancelListener(new OnCancelListener() {
						
						public void onCancel(DialogInterface dialog) {
							return;
						}
					}).show();
			
			return true;
		}
		case LIST_CHATS_ID:
			i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.SessionListActivity");
			startActivityForResult(i, 'S');
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	/*
	 * private void goToChatPage() { Intent i = new Intent(this, ChatPage.class); i.putExtra(Notepadv3.CONTACT_ID,
	 * id); startActivityForResult(i, ACTIVITY_CHAT); }
	 */

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		// fillData();

		// Bundle extras = intent.getExtras();
		// switch(requestCode) {
		// case ACTIVITY_CREATE:
		// String title = extras.getString(NotesDbAdapter.KEY_TITLE);
		// String body = extras.getString(NotesDbAdapter.KEY_BODY);
		// mDbHelper.createNote(title, body);
		// fillData();
		// break;
		// case ACTIVITY_EDIT:
		// Long rowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
		// if (rowId != null) {
		// String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
		// String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
		// mDbHelper.updateNote(rowId, editTitle, editBody);
		// }
		// fillData();
		// break;
		// }
	}

	private void initializeButton(final ImageButton contactButton, final TextView contactLabel,
			final String contactID) {
		contactButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				// Bundle bundle = new Bundle();
				// bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
				// bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
				// if (mRowId != null) {
				// bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
				// }
				// Intent mIntent = new Intent();
				// mIntent.putExtras(bundle);
				// setResult(RESULT_OK, mIntent);
				// setResult(RESULT_OK);
				// finish();

				Log.d(TAG, "Button of contact ID=" + contactID + " clicked!");

				if (contactsSelected.contains(contactID)) {
					contactsSelected.remove(contactID);
					contactLabel.setBackgroundColor(Color.TRANSPARENT);

					Log.d(TAG, "Changing color to unselect " + contactID + "!");
				} else {
					contactsSelected.add(contactID);
					contactLabel.setBackgroundColor(Color.RED);

					Log.d(TAG, "Changing color to show " + contactID + " is selected!");
				}

				// Intent i = new Intent();
				// i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.ChatPage");
				// i.putExtra(PrPlTalk.KEY_CONTACT_ID, contactID);
				// startActivityForResult(i, ACTIVITY_CHAT);
			}

		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		boolean b = super.onKeyDown(keyCode, event);

		switch (keyCode) {
		case KeyEvent.KEYCODE_S: {
			Intent i = new Intent();
			i.setClassName("edu.stanford.prpl.app.prpltalk.android", "edu.stanford.prpl.app.prpltalk.android.SessionListActivity");
			startActivityForResult(i, 'S');
			break;
		}
		}
		return b;
	}

}